package edu.whu.demo.dao;

import edu.whu.demo.entity.Commodity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface CommodityRepository extends JpaRepository<Commodity, Long>, JpaSpecificationExecutor<Commodity> {
    Commodity findCommodityById(long id);

    @Query(value = "select * from commodity where id in " +
            "(select commodity_id from commodity_suppliers where suppliers_id = ?1)", nativeQuery = true)
    List<Commodity> findCommoditiesBySupplier(long id);

    @Modifying
    @Query(value = "delete from commodity_suppliers where commodity_id = ?1", nativeQuery = true)
    void deleteByCommodityId(long id);

    @Modifying
    @Query(value = "insert into commodity_suppliers(c_id, s_id) values (?1, ?2)", nativeQuery = true)
    void insertRecord(long commodity_id, long supplier_id);

    Page<Commodity> findByNameContaining(String name, Pageable pageable);

    @Query(value = "select c from Commodity c where name = ?1")
    List<Commodity> findWithJPQLByName(String name);
}
